﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;


using System.IO;
using System.Net;
using System.Net.Sockets;

namespace Chapter26.Socket
{
    /// <summary>
    /// SocketSendWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SocketSendWindow : Window
    {
        public SocketSendWindow()
        {
            InitializeComponent();
        }

        private void sendButton_Click(object sender, RoutedEventArgs e)
        {
            Task.Run(() =>
            {
                var localhost = Dns.Resolve("localhost");
                var ipAddress = localhost.AddressList[0];
                var ipEndPoint = new IPEndPoint(ipAddress, 2112);
                var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(ipEndPoint);//连接到服务器 
                Dispatcher.Invoke(new Action(() =>
                {
                    var sendingMessage = Encoding.ASCII.GetBytes(sendTextBox.Text);
                    socket.Send(sendingMessage);//用界面的文本控件转成 ASCII 并发送服服务器
                }));
                var receivedBytes = new byte[1024];
                var totalReceivedBytes = socket.Receive(receivedBytes);//接收服务器的响应
                var receivedValue = Encoding.ASCII.GetString(receivedBytes, 0, totalReceivedBytes);
                Dispatcher.Invoke(new Action(() => sendTextBlock.Text = receivedValue));
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            });
        }
    }
}
